<template>
  <div class="login_container">
       <div>
           <img class="images" :src="images" alt="">
       </div>
       <el-tabs v-model="activeName" @tab-click="handleClick" stretch class="login_tabs">
            <!-- 登录区域 -->
            <el-tab-pane label="登录" name="first">
                <el-form ref="loginFormRef" :model="loginForm"
                :rules="loginFormRules" class="login_form">
                    <el-form-item prop="username">
                      <el-input v-model.trim="loginForm.username"
                      prefix-icon="iconfont icon-yonghuming"
                      placeholder="请输入用户名"
                      maxlength="18"
                      clearable
                      ></el-input>
                    </el-form-item>
                    <el-form-item  prop="password">
                      <el-input
                        type="password"
                        v-model.trim="loginForm.password"
                        prefix-icon="iconfont icon-mima"
                        placeholder="请输入密码"
                        maxlength="16"
                        clearable
                        show-password
                        @keyup.native.enter="onLogin"
                      ></el-input>
                    </el-form-item>
                    <el-row :gutter="33">
                      <el-col :span="16">
                        <el-form-item prop="code">
                          <el-input
                            v-model.trim="loginForm.code"
                            maxlength='5'
                            placeholder="请输入校验码"
                            clearable
                            prefix-icon="iconfont icon-yanzhengma"
                            @keyup.native.enter='onLogin'
                          ></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item>
                          <div class="code" @click="getCodeNum">
                            <span>{{codeNum}}</span>
                            <!-- <v-sidentify ref="sidentify" @getData="getData"></v-sidentify> -->
                          </div>
                           <!-- <drag-verify
                              ref="dragVerify7"
                              :width="390"
                              :height="40.8"
                              :isPassing.sync="isPassing7"
                              text="请按住滑块拖动"
                              textColor="#409EFF"
                              successText="验证通过"
                              handlerBg="#FFFFFF"
                              background="#EEEEEE"
                              handlerIcon="el-icon-right"
                              successIcon="el-icon-circle-check"
                              @passcallback="passcallback3"
                           >
                           </drag-verify> -->
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-form-item>
                      <el-button class="form_btn" type="primary"
                        @click="onLogin"
                        :loading="loginLoading">
                        <span>{{loginText}}</span>
                       </el-button>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
            <!-- 注册区域 -->
            <el-tab-pane label="注册" name="second">
                <el-form ref="registerFormRef" :rules="registerFormRules" :model="registerForm" class="register_form">
                    <el-form-item prop="username">
                      <el-input
                        v-model.trim="registerForm.username"
                        placeholder="请输入用户名"
                        prefix-icon="iconfont icon-yonghuming"
                        clearable
                      ></el-input>
                    </el-form-item>
                    <el-form-item prop="password">
                      <el-input
                        type="password"
                        v-model.trim="registerForm.password"
                        placeholder="请输入密码"
                        prefix-icon="iconfont icon-mima"
                        clearable
                        show-password
                      ></el-input>
                    </el-form-item>
                     <el-form-item prop="repassword">
                      <el-input
                        type="password"
                        v-model.trim="registerForm.repassword"
                        placeholder="请再次输入密码"
                        prefix-icon="iconfont icon-mima"
                        clearable
                        show-password
                        @keyup.native.enter="onRegister"
                        ></el-input>
                    </el-form-item>
                     <el-form-item>
                      <el-button class="form_btn"
                        type="primary"
                        @click="onRegister"
                        :loading="registerLoading"
                      >注 册</el-button>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
        </el-tabs>
        <div class="copyright">
          <h3>Copyright © 2022 ARMY-YANG</h3>
        </div>
  </div>
</template>

<script>
// 导入登录、注册方法
import { login, register } from '@/api/user'
import { adminLogin } from '@/api/admin'
import { getRandom } from '@/utils/code.js'
// 验证码组件
// import Sidentify  from '@/components/codenum'
// 基本滑块验证组件
// import dragVerify from "vue-drag-verify2"
export default {
  name: 'LoginIndex',
  components: {
  //  dragVerify
    // "v-sidentify":Sidentify
  },
  data () {
    // 注册验证
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.registerForm.repassword !== '') {
          this.$refs.registerFormRef.validateField('repassword')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    var validateCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入校验码'))
      } else if (value !== this.codeNum) {
        callback(new Error('校验码不正确，请从新输入'))
      } else {
        callback()
      }
    }
    return {
      isPassing7: false,
      // 导航默认状态
      activeName: 'first',
      // 登录按钮状态的Loading效果
      loginLoading: false,
      // 注册按钮状态的Loading效果
      registerLoading: false,
      // 登录文本
      loginText: '登 录',
      // 判断是否为管理员(admin)账号登录
      isAdmin: 'admin',
      // 验证码
      codeNum: '点击获取校验码',
      images: 'https://img1.baidu.com/it/u=1766971845,2226285315&fm=253&fmt=auto&app=138&f=JPEG?w=268&h=273',
      // 登录表单数据
      loginForm: {
        username: '',
        password: '',
        code: ''
      },
      // 注册表单数据
      registerForm: {
        username: '',
        password: '',
        repassword: ''// 确认密码
      },
      // 登录表单验证规则
      loginFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' }
        ],
        code: [
          { required: true, message: '请输入校验码', trigger: 'change' },
          { validator: validateCode, trigger: 'blur' }
        ]
      },
      // 注册表单验证规则
      registerFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'change' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'change' }
        ],
        password: [
          { validator: validatePass, trigger: 'change' },
          { min: 2, max: 16, message: '长度在 3 到 16 个字符', trigger: 'change' }
        ],
        repassword: [
          { validator: validatePass2, trigger: 'change' },
          { min: 2, max: 16, message: '长度在 3 到 16 个字符', trigger: 'change' }
        ]
      }
    }
  },

  mounted () {
    // this.getCodeNum()
  },

  methods: {
    // drawPic组件验证码的值
    // getData(code){
    //   console.log(code);
    //   this.codeNum = code
    // },
    passcallback3 () {
      // console.log('打印验证通过！：',this.isPassing7);
      if (!this.isPassing7) {
        return false
      }
      setTimeout(() => {
        this.onLogin()
      }, 500)
    },
    handleClick (tab, event) {
      // this.$refs.sidentify.drawPic()
      this.getCodeNum()
      this.codeNum = '点击获取校验码'
      this.isPassing7 = false
      // this.$refs.dragVerify7.reset()
      // 点击导航条重置表单
      this.$refs.loginFormRef.resetFields()
      this.$refs.registerFormRef.resetFields()
    },
    // 滑块如果验证通过的方法

    // 登录模块的方法
    onLogin () {
      // 登录表单预验证
      this.$refs.loginFormRef.validate(valid => {
        if (!valid) {
          return
        }
        if (this.loginForm.username === this.isAdmin) {
          // 管理员登录
          this.adminLogin()
          return
        }
        // 用户登录
        // if(!this.isPassing7){
        //   this.$message.error('请拖动滑块滑动验证！')
        //   return
        // }
        this.userLogin()
      })
    },
    // 创建随机验证码
    createdCodeNum () {
      const codeStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
      let codeNum = ''
      for (let i = 0; i < 5; i++) {
        const ran = getRandom(0, 62)
        codeNum += codeStr.charAt(ran)
      }
      this.codeNum = codeNum
    },
    // 获取验证码的方法
    getCodeNum () {
      this.createdCodeNum()
    },
    // 用户登录
    async userLogin () {
      this.loginLoading = true
      this.loginText = '登录中...'
      const { data: res } = await login(this.loginForm)
      if (res.status === 200) {
        this.loginLoading = false
        this.loginText = '登录'
        this.$message.success(res.description || '登录成功')
        // 保存用户token值
        window.localStorage.setItem('userToken', res.body.token)
        this.$router.push({
          name: 'Userhome'
        })
        return
      }
      this.$message.error(res.description || '你的账号或者密码异常')
      this.loginLoading = false
      this.loginText = '登录'
    },
    // 管理员登录
    async adminLogin () {
      this.loginLoading = true
      this.loginText = '登录中...'
      const { data: res } = await adminLogin(this.loginForm)
      if (res.status === 200) {
        this.loginLoading = false
        this.loginText = '登录'
        this.$message.success(res.description || '登录成功')
        // 保存管理员token值
        window.localStorage.setItem('adminToken', res.body.token)
        this.$router.push({
          name: 'adminLayout'
        })
        return
      }
      this.$message.error(res.description || '你的账号或者密码异常')
      this.loginLoading = false
      this.loginText = '登录'
    },
    // 注册模块的方法
    onRegister () {
      // 注册表单预验证
      this.$refs.registerFormRef.validate(valid => {
        if (!valid) {
          return false
        }
        this.userRegister()
      })
    },
    // 用户注册模块
    async userRegister () {
      this.registerLoading = true
      const { data: res } = await register(this.registerForm)
      if (res.status === 200) {
        this.registerLoading = false
        this.$message.success(res.description || '注册成功')
        this.$refs.registerFormRef.resetFields()
        setTimeout(() => {
          this.activeName = 'first'
        }, 1200)
      } else {
        this.registerLoading = false
        this.$message.error(res.description || '你输入的账号名重复')
      }
    }
  }
}
</script>

<style scoped >
    .login_container {
      position: fixed;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      background: url('../../assets/Login.jpg') ;
      background-size: cover;
      /* background-size: auto; */
    }
    .images {
      position: absolute;
      left: 45%;
      top: 8%;
      width: 150px;
      height: 150px;
      border-radius: 50%;
    }
    .login_tabs {
      width: 450px;
      /* margin-top: -200px; */
      background-color: #fff;
      /* background: rgba(255, 255, 255, .3); */
      border-radius: 10px;
    }
    .login_form, .register_form {
      padding: 30px;
    }
    .form_btn {
      margin-top: 10px;
      width: 100% !important;
    }
    .code {
      text-align: center;
      background:url('../../assets/codebg.png') no-repeat;
      color: #409EFF;
      /* font-size: 16px; */
      cursor: pointer;
      border-radius: 5px;
    }
    .copyright {
      position: absolute;
      bottom: 0;
      color: #fff;
    }
</style>
